﻿Imports System.Net

Namespace Coding4Fun.PrinterDisplayHack
	Public Class StockPrice
		Public Property TickerSymbol() As String

		Public Sub New(ByVal tickerSymbol As String)
			Me.TickerSymbol = tickerSymbol
		End Sub

		Public Function GetPriceFromYahoo(ByVal tickerSymbol As String) As String
			Dim price As String

			Dim url As String = String.Format("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes.csv%3Fs%3D{0}%26f%3Dsl1'%20and%20columns%3D'symbol%2Cprice'", tickerSymbol)

			Try
				Dim uri As New Uri(url)

				Dim req As HttpWebRequest = CType(WebRequest.Create(uri), HttpWebRequest)
				Dim resp As HttpWebResponse = CType(req.GetResponse(), HttpWebResponse)

				Dim doc As XDocument = XDocument.Load(resp.GetResponseStream())

				resp.Close()

				Dim ticker = From query In doc.Descendants("query") , results In query.Descendants("results") , row In query.Descendants("row") _
				             Let xElement = row.Element("price") _
				             Where xElement IsNot Nothing _
				             Select New With {Key .price = xElement.Value}

				price = ticker.First().price
			Catch ex As Exception
				price = "Exception retrieving symbol: " & ex.Message
			End Try

			Return price
		End Function

		Public Function GetPrice() As String
			Return GetPriceFromYahoo(TickerSymbol)
		End Function
	End Class
End Namespace
